import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

const GOODS_SESSION = 'goodsList_session'

const store = new Vuex.Store({
  state: {
    goodsList: [], // 总的商品列表
    cartGoodsList: [], // 购物车里的商品列表
    isCheckedAll: false // 全选按钮是否是选中状态
  },
  getters: {
    // 获取到购物车里的商品数量
    getCartGoodsNum (state) {
      return state.cartGoodsList.length
    },
    // 获取到已选商品的个数
    getCheckedGoodsNum (state) {
      let checkedGoods = state.cartGoodsList.filter(goods => goods.isChecked)
      return checkedGoods.length
    },
    // 计算总额
    getTotalPrice (state) {
      let price = state.cartGoodsList.reduce((acc, goods) => {
        if (goods.isChecked) {
          acc = Number((acc + goods.count * goods.price).toFixed(2))
        }
        return acc
      }, 0)
      return price
    },
    getCheckedGoods (state) { // 获取所有的选中的购物车商品
      return state.cartGoodsList.filter(goods => goods.isChecked)
    }
  },
  actions: {
    // 初始化获取商品列表
    getGoodsList () {
      fetch('/api/goodsList', {
        headers: {
          'accept': 'application/json'
        }
      }).then(res => res.json())
        .then(list => {
          console.log('请求成功！')
          store.commit('setGoodsList', list)
        }).catch(err => {
          console.error(err)
        })
    },
    // 把要买的商品发送到服务器
    sendGoods (store, callback) {
      fetch('/api/postGoods', {
        method: 'POST',
        body: JSON.stringify(store.getters.getCheckedGoods),
        headers: {
          'accept': 'application/json'
        }
      }).then(res => res.json())
        .then(data => {
          console.log('data: ', data)
          typeof callback === 'function' && callback()
        }).catch(err => console.error(err))
    }
  },
  mutations: {
    // 设置商品列表
    setGoodsList (state, list) {
      state.goodsList = list
    },
    // 设置购物车信息
    setCartGoodsList (state, list) {
      state.cartGoodsList = list
      // 如果所有的商品的 isChecked 都等于 true，需要让 isCheckedAll 为 true
      if (list.length && list.every(goods => goods.isChecked)) {
        store.commit('setBoolCheckedAll', true)
      }
    },
    // 添加商品到购物车
    pushGoods (state, goods) {
      var idx = state.cartGoodsList.findIndex(value => value.id === goods.id)
      // 如果等于 -1 才添加到购物车，不等于 -1 说明购物车里已经有了该商品
      if (idx === -1) {
        state.cartGoodsList.push(goods)
        store.commit('updateLocalSession') // 更新本地存储
      }
      store.commit('setBoolCheckedAll', false)
    },
    // 移除一件商品
    removeGoods (state, goodsId) {
      state.cartGoodsList = state.cartGoodsList.filter(goods => goods.id !== goodsId)
      // 移除商品之后，其他的商品是不是都是选中的
      let isCheckedAll = state.cartGoodsList.every(goods => goods.isChecked)
      if (isCheckedAll) store.commit('setBoolCheckedAll', true)
      store.commit('updateLocalSession') // 更新本地存储
    },
    // 移除选中的个别商品，当选中时，isChecked 的值将是 true
    removeAllGoods (state) {
      state.cartGoodsList = state.cartGoodsList.filter(goods => !goods.isChecked)
      if (!state.cartGoodsList.length && state.isCheckedAll) {
        store.commit('setBoolCheckedAll', false)
      }
      // 更新购物车信息
      store.commit('updateLocalSession')
    },
    // 这个叫 toggleCheckedAll 比较好
    setIsCheckedAll (state) {
      state.isCheckedAll = !state.isCheckedAll
      store.commit('checkedAllGoods')
    },
    setBoolCheckedAll (state, bool) {
      state.isCheckedAll = bool
    },
    // 点击全选时，把 isChecked 值全部设置成 true
    checkedAllGoods (state) {
      let bool = state.isCheckedAll
      state.cartGoodsList = state.cartGoodsList.map(goods => {
        goods.isChecked = bool
        return goods
      })
      store.commit('updateLocalSession') // 更新本地存储
    },
    // 设置某个商品复选框的状态，叫 toggleCheckedGoods 比较好
    checkedGoods (state, goodsId) {
      let flag = true
      state.cartGoodsList = state.cartGoodsList.map(goods => {
        if (goods.id === goodsId) {
          goods.isChecked = !goods.isChecked
        }
        if (!goods.isChecked) flag = false
        return goods
      })
      store.commit('setBoolCheckedAll', flag)
      store.commit('updateLocalSession') // 更新本地存储
    },
    // 点击增加按钮
    increment (state, goodsId) {
      state.cartGoodsList = state.cartGoodsList.map(goods => {
        if (goods.id === goodsId) {
          if (goods.count < goods.maxCount) {
            goods.count += 1
            goods.totalPrice = Number((goods.totalPrice + goods.price).toFixed(2))
          }
        }
        return goods
      })
      store.commit('updateLocalSession') // 更新本地存储
    },
    // 点击减少按钮
    decrement (state, goodsId) {
      state.cartGoodsList = state.cartGoodsList.map(goods => {
        if (goods.id === goodsId) {
          if (goods.count > 1) {
            goods.count -= 1
            goods.totalPrice = Number((goods.totalPrice - goods.price).toFixed(2))
          }
        }
        return goods
      })
      store.commit('updateLocalSession') // 更新本地存储
    },
    // 从本地存储中拿到商品，更新 cartGoodsList
    setLocalSession () {
      let storage = localStorage.getItem(GOODS_SESSION)
      if (storage && Array.isArray(JSON.parse(storage))) {
        // 如果有
        store.commit('setCartGoodsList', JSON.parse(storage))
      } else {
        // 没有就创建
        localStorage.setItem(GOODS_SESSION, '[]')
      }
    },
    // 更新本地存储
    updateLocalSession (state) {
      localStorage.setItem(GOODS_SESSION, JSON.stringify(state.cartGoodsList))
    }
  }
})
export default store
